<script setup>
import { ref, onMounted, nextTick } from "vue";
import { useTransition } from "@vueuse/core";
import $bus from "../../utils/bus";
// import { ChatLineRound, Male } from '@element-plus/icons-vue'
import { Delete, Edit, Search, Share, Upload } from "@element-plus/icons-vue";
import { getCustomerLineApi, getGoodsApi } from "@/api/tradeCommon";
import {
  getCategoryFirByParamsApi,
  getCategoryListByParamsApi,
  getCategorySecByParamsApi,
  getCustomerDataBySaleTypeApi,
  getCustomerListByParamsApi,
  getGoodsListByParamsApi,
  getOrderDetailByParamsApi,
  getRuleTradeGoodsSimulationApi,
  saveAllRuleTradeGoodsSimulationApi,
  getTitileByParamsApi
} from "@/api/tradeGoodsSimulation";
import { ElMessage, ElMessageBox } from "element-plus";
import * as echarts from "echarts";
import { useGoodsSimulationStore } from "@/stores/goodsSimulation";
const source = ref(0);
const outputValue = useTransition(source, {
  duration: 1500,
});

source.value = 172000;
const goodsSimulationStore = useGoodsSimulationStore()
/**
 * 设置
 */
const customerLine = ref([]);
const selectedCustomerLine = ref([]);
const open = ref(false);
const title = ref("弹出框dialog");
const formRef = ref(null);
const form = ref([]);
const colseReset = () => {
  form.value = [];
};
const closeDialog = () => {
  open.value = false;
  formRef.value.resetFields();
  colseReset();
};
const config = async () => {
  open.value = true;
  title.value = "设置";
  const res = await getCustomerLineApi();
  customerLine.value = res.data;
  const ress = await getRuleTradeGoodsSimulationApi();
  selectedCustomerLine.value = ress.data;
};
const submit = () => {
  ElMessageBox.confirm("确认修改？", "确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await saveAllRuleTradeGoodsSimulationApi(
        selectedCustomerLine.value
      );
      ElMessage({
        type: "success",
        message: res.data,
      });
      closeDialog();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
/**
 * 获取虚拟商品
 */
const goods = ref([]);
const goodsFormRef = ref(null)
const goodsOpen = ref(false);
const goodsForm = ref({
  goodsId: "",
  goodsName: "",
  customerLine: "",
  unitSalePrice: 0,
  unitCostPrice: 0,
});
const goodsFormRule = ref({
  goodsName: [{ required: true, message: "不能为空", trigger: "blur" }],
  customerLine: [{ required: true, message: "不能为空", trigger: "blur" }],
  unitSalePrice: [{ required: true, message: "不能为空", trigger: "blur" }],
  unitCostPrice: [{ required: true, message: "不能为空", trigger: "blur" }],
  goodsId: [{ required: true, message: "请勾选商品", trigger: "blur" }],
});
const goodsCloseDialog = () => {
  goodsOpen.value = false;
  goodsFormRef.value.resetFields()
  goodsRefresh();
};
const saveGoods = async () => {
  const res = await getCustomerLineApi();
  customerLine.value = res.data;
  const ress = await getGoodsApi();
  goods.value = ress.data;
  goodsOpen.value = true;
};
//根据用户输入的内容（queryString）过滤建议列表。如果用户没有输入内容，则返回所有建议项。调用 cb(results) 将过滤后的结果传给 el-autocomplete 组件。
const goodsQuerySearch = (queryString, cb) => {
  const results = queryString
    ? goods.value.filter(createFilter(queryString))
    : goods.value;
  // console.log(results.length);
  // console.log(results);
  cb(
    results.map((item) => ({
      ...item,
      value: item.goodsName, // Element UI 需要这个字段
    }))
  );
};
//创建一个过滤器函数，用于匹配用户输入的内容。检查建议项的 value 是否以用户输入的内容开头（不区分大小写）。
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.goodsName.toLowerCase().indexOf(queryString.toLowerCase()) ===
      0
    );
  };
};
//选中自动输入框的建议时，触发的事件
const handleSelect = (item) => {
  //item是我们选中的建议中的那个选项（是一个对象）
  // alert(JSON.stringify(item));
  console.log(item);
  goodsForm.value.goodsName = item.goodsName;
  goodsForm.value.goodsId = item.id;
};
const goodsRefresh = () => {
  goodsForm.value = {
    goodsId: "",
    goodsName: "",
    customerLine: "",
    unitSalePrice: 0,
    unitCostPrice: 0,
  };
};
const goodsSubmit = () => {
  console.log(goodsForm.value)
  goodsFormRef.value.validate(async (valid) => {
      if (!valid) {
        return
      }
      goodsSimulationStore.addGoodsSimulationList(goodsForm.value)
      goodsRefresh()
    })

};

/**
 * -获取查询刷新
 */
const queryPageParams = ref({
  categoryFirId: undefined,
  categorySecId: undefined,
  saleType: undefined,
  customerId: undefined,
  goodsId: undefined,
  simulationGoodsList: goodsSimulationStore.goodsSimulationList,
  customerLine: "",
  // dateTime: [
  //   new Date().toISOString().split("T")[0], // 今天
  //   new Date().toISOString().split("T")[0], // 今天
  // ],
  dateTime: [
    "2025-09-01", // 今天
    "2025-09-01", // 今天
  ],
});
/**
 * getTitileByParamsApi
 */
const titleText = ref()
const getTitileByParams = async() => {
  const res = await getTitileByParamsApi(queryPageParams.value)
  titleText.value = res.data.data[0]
}

// ________________________________________一级分类________________________________________
/**
 * 一级分类
 */
const categoryFirRef = ref(null);
const categoryFirData = ref();
var categoryFirChart;
const getCategoryFirByParams = async () => {
  const res = await getCategoryFirByParamsApi(queryPageParams.value);
  categoryFirData.value = res.data;
  var option = {
    title: {
      text: categoryFirData.value?.text,
      subtext: categoryFirData.value?.subtext,
      left: "left",
    },
    tooltip: {
      trigger: "item",
      // 丰富的提示框内容
      formatter: function (params) {
        const data = params.data;
        return `
          <div style="font-weight:bold;">${data.name}</div>
          <div>销售额: ¥${(data.salePrice / 10000).toFixed(2)}万元</div>
          <div>成本: ¥${(data.costPrice / 10000).toFixed(2)}万元</div>
          <div>毛利额: ¥${(data.grossPrice / 10000).toFixed(2)}万元</div>
          <div>毛利率: ${(data.grossMargin * 100).toFixed(2)}%</div>
        `;
      },
    },
    series: [
      {
        name: "姓名",
        type: "pie",
        radius: "55%",
        center: ["40%", "50%"],
        data: categoryFirData.value.data.map((item) => ({
          name: item.categoryName,
          value: item.salePrice,
          // 保留原始数据供 tooltip 使用
          salePrice: item.salePrice,
          grossMargin: item.grossMargin,
          costPrice: item.costPrice,
          grossPrice: item.grossPrice,
          categoryId: item.categoryId,
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        label: {
          show: true,
          formatter: "{b}: {c} ({d}%)",
          fontSize: 12,
        },
        labelLine: {
          length: 10,
          length2: 5,
        },
      },
    ],
  };
  if (
    categoryFirChart != null &&
    categoryFirChart != "" &&
    categoryFirChart != undefined
  ) {
    categoryFirChart.dispose(); //销毁
  }
  // 基于准备好的dom，初始化echarts实例
  categoryFirChart = echarts.init(categoryFirRef.value);
  option && categoryFirChart.setOption(option);
  // 添加点击事件监听
  categoryFirChart.on("click", (params) => {
    if (!queryPageParams.value.categoryFirId) {
      queryPageParams.value.categoryFirId = params.data.categoryId;
    } else {
      queryPageParams.value.categoryFirId = undefined;
    }
    getAllData();
  });
};

/**
 * 二级分类
 */
const categorySecRef = ref(null);
const categorySecData = ref();
var categorySecChart;
const getCategorySecByParams = async () => {
  const res = await getCategorySecByParamsApi(queryPageParams.value);
  categorySecData.value = res.data;
  var option = {
    title: {
      text: categorySecData.value?.text,
      subtext: categorySecData.value?.subtext,
      left: "left",
    },
    tooltip: {
      trigger: "item",
      // 丰富的提示框内容
      formatter: function (params) {
        const data = params.data;
        return `
          <div style="font-weight:bold;">${data.name}</div>
          <div>销售额: ¥${(data.salePrice / 10000).toFixed(2)}万元</div>
          <div>成本: ¥${(data.costPrice / 10000).toFixed(2)}万元</div>
          <div>毛利额: ¥${(data.grossPrice / 10000).toFixed(2)}万元</div>
          <div>毛利率: ${(data.grossMargin * 100).toFixed(2)}%</div>
        `;
      },
    },
    series: [
      {
        name: "姓名",
        type: "pie",
        radius: "55%",
        center: ["40%", "50%"],
        data: categorySecData.value.data.map((item) => ({
          name: item.categoryName,
          value: item.salePrice,
          // 保留原始数据供 tooltip 使用
          salePrice: item.salePrice,
          grossMargin: item.grossMargin,
          costPrice: item.costPrice,
          grossPrice: item.grossPrice,
          categoryId: item.categoryId,
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        label: {
          show: true,
          formatter: "{b}: {c} ({d}%)",
          fontSize: 12,
        },
        labelLine: {
          length: 10,
          length2: 5,
        },
      },
    ],
  };
  if (
    categorySecChart != null &&
    categorySecChart != "" &&
    categorySecChart != undefined
  ) {
    categorySecChart.dispose(); //销毁
  }
  // 基于准备好的dom，初始化echarts实例
  categorySecChart = echarts.init(categorySecRef.value);
  option && categorySecChart.setOption(option);
  // 添加点击事件监听
  categorySecChart.on("click", (params) => {
    if (!queryPageParams.value.categorySecId) {
      queryPageParams.value.categorySecId = params.data.categoryId;
    } else {
      queryPageParams.value.categorySecId = undefined;
    }
    getAllData();
  });
};
/**
 * 分类列表
 */
const categoryListRef = ref(null);
const categoryListData = ref();
var categoryListChart;
const getCategoryListByParams = async () => {
  const res = await getCategoryListByParamsApi(queryPageParams.value);
  categoryListData.value = res.data;
  var option = {
    title: {
      text: categoryListData.value?.text,
      subtext: categoryListData.value?.subtext,
      left: "left",
    },
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        const data = params[2].data;
        return `
        <div style="font-weight:bold;">${data.categoryName}</div>
        <div>销售额: ¥${(data.salePrice / 10000).toFixed(2)}万元</div>
          <div>成本: ¥${(data.costPrice / 10000).toFixed(2)}万元</div>
          <div>毛利额: ¥${(data.grossPrice / 10000).toFixed(2)}万元</div>
          <div>毛利率: ${(data.grossMargin * 100).toFixed(2)}%</div>
        `;
      },
    },
    legend: {
      data: ["销售额", "毛利率"], // 只显示这两个系列的图例
    },
    xAxis: {
      type: "value",
      boundaryGap: [0, 0.01],
    },
    yAxis: {
      type: "category",
      data: categoryListData.value.data.map((item) => item.categoryName),
      // inverse: false, // 不要反转，保持数据原有顺序
      inverse: true,
    },
    series: [
      {
        name: "销售额",
        type: "bar",
        data: categoryListData.value.data.map((item) =>
          (item.salePrice / 10000).toFixed(2)
        ),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        label: {
          show: true,
          position: "right", // 标签位置在柱状图顶部
          formatter: "{c}万", // 简化显示格式
          fontSize: 11,
          fontWeight: "bold",
          // color: "#333",
          color: "#5470c6", // 与销售额柱状图主色一致
          shadowBlur: 2,
          shadowColor: "rgba(84, 112, 198, 0.3)", // 蓝色阴影
          shadowOffsetX: 0,
          shadowOffsetY: 1,
        },
        labelLine: {
          show: false, // 柱状图通常不需要连接线
        },
        itemStyle: {
          color: "#5470c6", // 与label颜色一致
        },
      },
      {
        name: "毛利率",
        type: "bar",
        data: categoryListData.value.data.map((item) =>
          (item.grossMargin * 100).toFixed(2)
        ),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.1)",
          },
        },
        label: {
          show: true,
          position: "right", // 标签位置在柱状图顶部
          formatter: "{c}%", // 简化显示格式
          fontSize: 11,
          fontWeight: "bold",
          // color: "#333",
          color: "#91CC75", // 毛利率专用红色
          shadowBlur: 2,
          shadowColor: "rgba(0, 0, 0, 0.1)", // 使用同色系阴影
          shadowOffsetX: 0,
          shadowOffsetY: 1,
        },
        labelLine: {
          show: false, // 柱状图通常不需要连接线
        },
        itemStyle: {
          color: "#91CC75", // 与label颜色一致
        },
      },

      {
        name: "整体数据",
        show: false,
        type: "bar",
        data: categoryListData.value.data.map((item) => item),
      },
    ],
  };
  if (
    categoryListChart != null &&
    categoryListChart != "" &&
    categoryListChart != undefined
  ) {
    categoryListChart.dispose(); //销毁
  }
  // 基于准备好的dom，初始化echarts实例
  categoryListChart = echarts.init(categoryListRef.value);
  option && categoryListChart.setOption(option);
  // 添加点击事件监听
  categoryListChart.on("click", (params) => {
    console.log(params.value);
  });
};
/**
 * 客户类型
 */
const customerTypeRef = ref(null);
const customerTypeData = ref();
var customerTypChart;
const getCustomerDataBySaleType = async () => {
  const res = await getCustomerDataBySaleTypeApi(queryPageParams.value);
  customerTypeData.value = res.data;
  // console.log(customerTypeData.value?.data);
  var option = {
    title: {
      text: customerTypeData.value?.text,
      subtext: customerTypeData.value?.subtext,
      left: "left",
    },
    tooltip: {
      trigger: "item",
      // 丰富的提示框内容
      formatter: function (params) {
        const data = params.data;
        return `
          <div style="font-weight:bold;">${data.name}</div>
          <div>销售额: ¥${(data.salePrice / 10000).toFixed(2)}万元</div>
          <div>成本: ¥${(data.costPrice / 10000).toFixed(2)}万元</div>
          <div>毛利额: ¥${(data.grossPrice / 10000).toFixed(2)}万元</div>
          <div>毛利率: ${(data.grossMargin * 100).toFixed(2)}%</div>
        `;
      },
    },
    legend: {
      orient: "vertical",
      bottom: "bottom",
    },
    series: [
      {
        name: "姓名",
        type: "pie",
        radius: "55%",
        center: ["40%", "50%"],
        data: customerTypeData.value.data.map((item) => ({
          name: item.typeStr,
          value: item.salePrice,
          typeValue: item.typeValue,
          // 保留原始数据供 tooltip 使用
          typeStr: item.typeStr,
          salePrice: item.salePrice,
          grossMargin: item.grossMargin,
          costPrice: item.costPrice,
          grossPrice: item.grossPrice,
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        label: {
          show: true,
          formatter: "{b}: {c} ({d}%)",
          fontSize: 12,
        },
        labelLine: {
          length: 10,
          length2: 5,
        },
      },
    ],
  };
  if (
    customerTypChart != null &&
    customerTypChart != "" &&
    customerTypChart != undefined
  ) {
    customerTypChart.dispose(); //销毁
  }
  // 基于准备好的dom，初始化echarts实例
  customerTypChart = echarts.init(customerTypeRef.value);
  option && customerTypChart.setOption(option);
  // 添加点击事件监听
  customerTypChart.on("click", (params) => {
    console.log(params.data.typeValue);
    if (!queryPageParams.value.saleType) {
      queryPageParams.value.saleType = params.data.typeValue;
    } else {
      queryPageParams.value.saleType = undefined;
    }
    getAllData();
  });
};
/**
 * 客户路线
 */
const customerLineRef = ref(null);
const customerLineData = ref();
var customerLineChart;
const getCustomerListByParams = async () => {
  const res = await getCustomerListByParamsApi(queryPageParams.value);
  customerLineData.value = res.data;
  var option = {
    title: {
      text: customerLineData.value?.text,
      subtext: customerLineData.value?.subtext,
      left: "left",
    },
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        const data = params[2].data;
        return `
        <div style="font-weight:bold;">${data.customerLine}</div>
        <div>销售额: ¥${(data.salePrice / 10000).toFixed(2)}万元</div>
          <div>成本: ¥${(data.costPrice / 10000).toFixed(2)}万元</div>
          <div>毛利额: ¥${(data.grossPrice / 10000).toFixed(2)}万元</div>
          <div>毛利率: ${(data.grossMargin * 100).toFixed(2)}%</div>
        `;
      },
    },
    legend: {
      data: ["销售额", "毛利率"], // 只显示这两个系列的图例
    },
    xAxis: {
      type: "value",
      boundaryGap: [0, 0.01],
    },
    yAxis: {
      type: "category",
      triggerEvent: true,
      data: customerLineData.value.data.map((item) => item.customerLine),
      // axisLabel: {
      //     formatter: `{value}1111111%`,
      //   },
      inverse: true,
    },
    series: [
      {
        name: "销售额",
        type: "bar",
        data: customerLineData.value.data.map((item) =>
          (item.salePrice / 10000).toFixed(2)
        ),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        label: {
          show: true,
          position: "right", // 标签位置在柱状图顶部
          formatter: "{c}万", // 简化显示格式
          fontSize: 11,
          fontWeight: "bold",
          // color: "#333",
          color: "#5470c6", // 与销售额柱状图主色一致
          shadowBlur: 2,
          shadowColor: "rgba(84, 112, 198, 0.3)", // 蓝色阴影
          shadowOffsetX: 0,
          shadowOffsetY: 1,
        },
        labelLine: {
          show: false, // 柱状图通常不需要连接线
        },
        itemStyle: {
          color: "#5470c6", // 与label颜色一致
        },
      },
      {
        name: "毛利率",
        type: "bar",
        data: customerLineData.value.data.map((item) =>
          (item.grossMargin * 100).toFixed(2)
        ),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.1)",
          },
        },
        label: {
          show: true,
          position: "right", // 标签位置在柱状图顶部
          formatter: "{c}%", // 简化显示格式
          fontSize: 11,
          fontWeight: "bold",
          // color: "#333",
          color: "#91CC75", // 毛利率专用红色
          shadowBlur: 2,
          shadowColor: "rgba(0, 0, 0, 0.1)", // 使用同色系阴影
          shadowOffsetX: 0,
          shadowOffsetY: 1,
        },
        labelLine: {
          show: false, // 柱状图通常不需要连接线
        },
        itemStyle: {
          color: "#91CC75", // 与label颜色一致
        },
      },
      {
        name: "整体数据",
        show: false,
        type: "bar",
        data: customerLineData.value.data.map((item) => item),
      },
    ],
  };
  if (
    customerLineChart != null &&
    customerLineChart != "" &&
    customerLineChart != undefined
  ) {
    customerLineChart.dispose(); //销毁
  }
  // 基于准备好的dom，初始化echarts实例
  customerLineChart = echarts.init(customerLineRef.value);
  option && customerLineChart.setOption(option);

  // 在图表初始化后添加点击事件监听
  customerLineChart.on("click", function (params) {
    if (params.componentType === "yAxis") {
      // 点击的是Y轴
      const clickedValue = params.value; // 获取点击的Y轴值
      const clickedIndex = params.dataIndex; // 获取点击的索引

      console.log("点击的Y轴值:", clickedValue);
      console.log("点击的索引:", clickedIndex);
      console.log("完整参数:", params);
      if (!queryPageParams.value.customerLine) {
        queryPageParams.value.customerLine = clickedValue;
      } else {
        queryPageParams.value.customerLine = undefined;
      }
      getAllData();
    }
  });
};

/**
 * 商品列表
 */

const goodsRef = ref(null);
const goodsData = ref();
var goodsRefChart;
const getGoodsListByParams = async () => {
  const res = await getGoodsListByParamsApi(queryPageParams.value);
  goodsData.value = res.data;
  var option = {
    title: {
      text: goodsData.value?.text,
      subtext: goodsData.value?.subtext,
      left: "left",
    },
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        const data = params[2].data;
        return `
        <div style="font-weight:bold;">${data.goodsName}</div>
        <div>销售额: ¥${(data.salePrice / 10000).toFixed(2)}万元</div>
          <div>成本额: ¥${(data.costPrice / 10000).toFixed(2)}万元</div>
          <div>毛利额: ¥${(data.grossPrice / 10000).toFixed(2)}万元</div>
          <div>销售单价: ¥${(data.unitSalePrice ).toFixed(2)}元</div>
          <div>成本单价: ¥${(data.unitCostPrice ).toFixed(2)}元</div>
          <div>毛利率: ${(data.grossMargin * 100).toFixed(2)}%</div>
        `;
      },
    },
    legend: {
      data: ["销售额", "毛利率"], // 只显示这两个系列的图例
    },
    xAxis: {
      type: "value",
      boundaryGap: [0, 0.01],
    },
    dataZoom: [
      {
        type: "inside",
        yAxisIndex: 0,
        zoomOnMouseWheel: false, // 禁用滚轮缩放
        moveOnMouseWheel: true, // 启用滚轮平移
        filterMode: "filter", // 过滤模式
        startValue: 0, // 从第一条数据开始
        endValue: 9, // 显示到第10条数据
        minValueSpan: 10, // 最小显示10条
        maxValueSpan: 10, // 最大显示10条
        throttle: 50, // 滚动节流
        orient: "vertical", // 垂直方向
        // 关键：设置滚轮方向，让向下滚动显示更多数据
        moveOnMouseWheel: true,
        zoomOnMouseWheel: false,
      },
    ],
    yAxis: {
      type: "category",
      triggerEvent: true,
      inverse: true, // 关键：让数据从上到下显示
      data: goodsData.value.data.map((item) => item.goodsName),
      axisLabel: {
        // interval: 0, // 显示所有标签
        formatter: function (data) {
          // 文字过长时显示省略号
          // console.log(value)
          if (data > 6) {
            return data.substring(0, 6) + "...";
          }
          return data;
        },
      },
    },
    series: [
      {
        name: "销售额",
        type: "bar",
        data: goodsData.value.data.map((item) =>
          (item.salePrice / 10000).toFixed(2)
        ),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        label: {
          show: true,
          position: "right", // 标签位置在柱状图顶部
          formatter: "{c}万", // 简化显示格式
          fontSize: 11,
          fontWeight: "bold",
          // color: "#333",
          color: "#5470c6", // 与销售额柱状图主色一致
          shadowBlur: 2,
          shadowColor: "rgba(84, 112, 198, 0.3)", // 蓝色阴影
          shadowOffsetX: 0,
          shadowOffsetY: 1,
        },
        labelLine: {
          show: false, // 柱状图通常不需要连接线
        },
        itemStyle: {
          color: "#5470c6", // 与label颜色一致
        },
      },
      {
        name: "毛利率",
        type: "bar",
        data: goodsData.value.data.map((item) =>
          (item.grossMargin * 100).toFixed(2)
        ),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.1)",
          },
        },
        label: {
          show: true,
          position: "right", // 标签位置在柱状图顶部
          formatter: "{c}%", // 简化显示格式
          fontSize: 11,
          fontWeight: "bold",
          // color: "#333",
          color: "#91CC75", // 毛利率专用红色
          shadowBlur: 2,
          shadowColor: "rgba(0, 0, 0, 0.1)", // 使用同色系阴影
          shadowOffsetX: 0,
          shadowOffsetY: 1,
        },
        labelLine: {
          show: false, // 柱状图通常不需要连接线
        },
        itemStyle: {
          color: "#91CC75", // 与label颜色一致
        },
      },
      {
        name: "整体数据",
        show: false,
        type: "bar",
        data: goodsData.value.data.map((item) => item),
      },
    ],
  };
  if (
    goodsRefChart != null &&
    goodsRefChart != "" &&
    goodsRefChart != undefined
  ) {
    goodsRefChart.dispose(); //销毁
  }
  // 基于准备好的dom，初始化echarts实例
  goodsRefChart = echarts.init(goodsRef.value);
  option && goodsRefChart.setOption(option);
  // 在图表初始化后添加点击事件监听
  goodsRefChart.on("click", function (params) {
    if (params.componentType === "yAxis") {
      // 点击的是Y轴
      // const clickedValue = params.value; // 获取点击的Y轴值
      const dataIndex = params.dataIndex; // 获取点击的索引
      const goods = goodsData.value.data[dataIndex];
      if (!queryPageParams.value.goodsId) {
        queryPageParams.value.goodsId = goods.goodsId;
      } else {
        queryPageParams.value.goodsId = undefined;
      }
      getAllData();
    }
  });
};
/**
 * 订单详情
 */
const orderDetailData = ref();
const orderDetailTitleData = ref();
const getOrderDetailByParams = async () => {
  const res = await getOrderDetailByParamsApi(queryPageParams.value);
  orderDetailData.value = res.data.data;
  orderDetailTitleData.value = res.data.text;
};
/**
 * 获取数据（总）
 */
const getAllData = async () => {
  await Promise.all([
    getCategoryFirByParams(),
    getCategorySecByParams(),
    getCategoryListByParams(),
    getCustomerDataBySaleType(),
    getCustomerListByParams(),
    getGoodsListByParams(),
    getOrderDetailByParams(),
    getTitileByParams()
  ]);
};
const dateTimeChang = async () => {
  await Promise.all([
    getCategoryFirByParams(),
    getCategorySecByParams(),
    getCategoryListByParams(),
    getCustomerDataBySaleType(),
    getCustomerListByParams(),
    getGoodsListByParams(),
    getOrderDetailByParams(),
    getTitileByParams()
  ]);
};
const allRefresh = async() => {
  queryPageParams.value = {
    categoryFirId: undefined,
  categorySecId: undefined,
  saleType: undefined,
  customerId: undefined,
  goodsId: undefined,
  simulationGoodsList: goodsSimulationStore.goodsSimulationList,
  customerLine: "",
  dateTime: queryPageParams.value.dateTime
  // dateTime: [
  //   new Date().toISOString().split("T")[0], // 今天
  //   new Date().toISOString().split("T")[0], // 今天
  // ],
  // dateTime: [
  //   "2025-09-01", // 今天
  //   "2025-09-01", // 今天
  // ],
  }
  await Promise.all([
    getCategoryFirByParams(),
    getCategorySecByParams(),
    getCategoryListByParams(),
    getCustomerDataBySaleType(),
    getCustomerListByParams(),
    getGoodsListByParams(),
    getOrderDetailByParams(),
    getTitileByParams()
  ]);
}
//---------------------------------------------------------------------获取标题事件---------------------------------------------------------------------
const titleData = ref({
  titleFir: "贸易模拟",
  titleSec: "商品模拟",
});

onMounted(async () => {
  $bus.emit("title-info", titleData.value);
  await Promise.all([
    getCategoryFirByParams(),
    getCategorySecByParams(),
    getCategoryListByParams(),
    getCustomerDataBySaleType(),
    getCustomerListByParams(),
    getGoodsListByParams(),
    getOrderDetailByParams(),
    getTitileByParams()
  ]);
});
</script>
<template>
  <el-card>
    <el-row :gutter="16">
      <el-col :xs="24" :sm="12" :md="6" class="text-center mb-4">

        <el-statistic :precision="2" title="销售额" :value="titleText?.salePrice" />

      </el-col>

      <el-col :xs="24" :sm="12" :md="6" class="text-center mb-4">

        <el-statistic :precision="2" title="成本额" :value="titleText?.costPrice" />

      </el-col>

      <el-col :xs="24" :sm="12" :md="6" class="text-center mb-4">

        <el-statistic :precision="2" title="毛利额" :value="titleText?.grossPrice" />

      </el-col>

      <el-col :xs="24" :sm="12" :md="6" class="text-center mb-4">

        <el-statistic :precision="2" title="毛利率" :value="titleText?.grossMargin" />

      </el-col>
    </el-row>
  </el-card>

  <el-card>
    <el-row :gutter="20">
      <el-col :span="10">
        <el-date-picker
          v-model="queryPageParams.dateTime"
          type="daterange"
          range-separator="To"
          start-placeholder="Start date"
          end-placeholder="End date"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          size="large"
          @change="dateTimeChang"
        />
      </el-col>

      <el-col :span="2">
        <el-button type="primary" size="large" @click="config()">
          <el-icon :size="30">
            <Setting />
          </el-icon>
        </el-button>
      </el-col>

      <el-col :span="2">
        <el-button type="primary" size="large" @click="saveGoods()">
          <el-icon :size="30">
            <Connection />
          </el-icon>
        </el-button>
      </el-col>

      <el-col :span="2">
        <el-button type="primary" size="large" @click="allRefresh()">
          <el-icon :size="30">
            <RefreshRight />
          </el-icon>
        </el-button>
      </el-col>
    </el-row>
  </el-card>

  <el-row :gutter="20">
    <el-col :span="8">
      <el-card>
        <div ref="customerTypeRef" style="width: 400px; height: 400px"></div>
      </el-card>
    </el-col>
    <el-col :span="16">
      <el-card>
        <div
          ref="customerLineRef"
          style="width: 800px; height: 400px"
        ></div> </el-card
    ></el-col>
  </el-row>

  <el-row :gutter="20">
    <el-col :span="8">
      <el-card>
        <div ref="categoryFirRef" style="width: 400px; height: 400px"></div>
      </el-card>
    </el-col>
    <el-col :span="8">
      <el-card>
        <div
          ref="categorySecRef"
          style="width: 400px; height: 400px"
        ></div> </el-card
    ></el-col>
    <el-col :span="8">
      <el-card>
        <div
          ref="categoryListRef"
          style="width: 400px; height: 400px"
        ></div> </el-card
    ></el-col>
  </el-row>

  <el-row :gutter="20">
    <el-col :span="12">
      <el-card>
        <div ref="goodsRef" style="width: 800px; height: 400px"></div>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card>
        <span style="font-weight: 1000; font-size: large">{{
          orderDetailTitleData
        }}</span>
        <el-table :data="orderDetailData" style="width: 100%; height: 375px">
          <el-table-column prop="goodsName" label="商品名称" width="160" />
          <el-table-column prop="unitStr" label="单位" />
          <el-table-column prop="saleNum" label="数量" />
          <el-table-column prop="unitPrice" label="单价" />
          <el-table-column prop="unitCostPrice" label="单位成本" />
          <el-table-column prop="salePrice" label="销售额" />
          <el-table-column prop="costPrice" label="成本" />
          <el-table-column prop="createTime" label="时间" width="160" />
        </el-table> </el-card
    ></el-col>
  </el-row>

  <!-- 设置 -->
  <el-dialog
    v-model="open"
    :title="title"
    width="80%"
    :before-close="closeDialog"
    draggable
  >
    <el-form :model="form" label-width="auto" ref="formRef">
      <el-transfer
        :titles="['全部客户路线', '已选路线']"
        v-model="selectedCustomerLine"
        :data="customerLine"
        :props="{
          key: 'value',
          label: 'desc',
        }"
      />
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog()">取消</el-button>
        <el-button type="primary" @click="submit()"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 添加虚拟商品 -->
  <el-dialog
    v-model="goodsOpen"
    title="虚拟商品"
    width="80%"
    :before-close="goodsCloseDialog"
    draggable
  >
    <el-form
      :model="goodsForm"
      label-width="auto"
      ref="goodsFormRef"
      :rules="goodsFormRule"
    >
      <el-form-item label="商品名称" prop="goodsName">
        <!-- <el-input v-model="goodsForm.goodsName" /> -->
        <el-autocomplete
          v-model="goodsForm.goodsName"
          :fetch-suggestions="goodsQuerySearch"
          clearable
          class="w-50"
          placeholder="请输入商品"
          @select="handleSelect"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerLine">
        <el-select
          v-model="goodsForm.customerLine"
          placeholder="请选择客户名称"
          size="large"
          style="width: 240px"
        >
          <el-option
            v-for="item in customerLine"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售单价" prop="unitSalePrice">
        <el-input v-model="goodsForm.unitSalePrice" type="number" />
      </el-form-item>
      <el-form-item label="成本单价" prop="unitCostPrice">
        <el-input v-model="goodsForm.unitCostPrice" type="number" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="goodsCloseDialog()">取消</el-button>
        <el-button @click="goodsRefresh()">刷新</el-button>
        <el-button type="primary" @click="goodsSubmit()"> 确定 </el-button>
      </div>

      <el-table :data="goodsSimulationStore.goodsSimulationList" style="width: 100%; height: 375px">
          <el-table-column prop="goodsName" label="商品名称" width="160" />
          <el-table-column prop="customerLine" label="客户路线" />
          <el-table-column prop="unitSalePrice" label="销售单价" />
          <el-table-column prop="unitCostPrice" label="成本单价" />
          <el-table-column   width="150" label="操作">
        <template #default="data">
          <el-button icon="Delete" link type="danger" size="small" @click="goodsSimulationStore.delGoodsSimulationList(data.row)">删除</el-button>
        </template>
      </el-table-column>
        </el-table>

    </template>
  </el-dialog>
</template>
<style lang="scss" scope>
.chart {
  width: 100%;
  height: 100vh;
}
</style>
